//
//  MeRegisterLoginInputFieldView.m
//  ZITHER
//
//  Created by weixin on 2019/1/16.
//  Copyright © 2019 weixn. All rights reserved.
//

#import "MeRegisterLoginInputFieldView.h"
#import "MeRegisterRegisterVC.h"
#import <UMPush/UMessage.h>
#import "LoginSetPasswordView.h"

@interface MeRegisterLoginInputFieldView()<QMUITextFieldDelegate>

@property (nonatomic,strong)QMUITextField *fieldLogin;
@property (nonatomic,strong)QMUITextField *fieldPassword;
@property (nonatomic,strong)UIButton *eyebtn;

@property (nonatomic,strong)BaseBtn *loginbtn;
@property (nonatomic,strong)BaseBtn *forgetbtn;
@property (nonatomic,strong)BaseLab *redTipe;//报错提示

@end

@implementation MeRegisterLoginInputFieldView

- (instancetype)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if (self) {
    
        [self setUI];
        [self setMasonry];

    }
    return self;
}


-(void)setUI{
    [self addLogo];
    [self addSubview:self.fieldLogin];
    [self addSubview:self.fieldPassword];
    [self addSubview:self.eyebtn];
    [self addSubview:self.loginbtn];
    [self addSubview:self.forgetbtn];
}

-(void)setMasonry{
    
    [self.fieldLogin mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(self).offset(15);
        make.right.equalTo(self).offset(-15);
        make.height.mas_equalTo(40);
        make.top.equalTo(self).offset(110);
    }];
    
    [self.fieldPassword mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(self).offset(15);
        make.right.equalTo(self).offset(-15);
        make.height.mas_equalTo(40);
        make.top.equalTo(self.fieldLogin.mas_bottom).offset(20);
    }];
    
    [self.eyebtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.right.equalTo(self.fieldPassword).offset(0);
        make.top.equalTo(self.fieldPassword).offset(0);
        make.height.width.mas_equalTo(36);
    }];
    
    [self.loginbtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.fieldPassword.mas_bottom).offset(50);
        make.left.equalTo(self).offset(15);
        make.right.equalTo(self).offset(-15);
        make.height.mas_equalTo(45);
    }];
    
    
    [self addSubview:self.redTipe];
    
    [self.forgetbtn mas_makeConstraints:^(MASConstraintMaker *make) {
        //        make.top.equalTo(self.fieldPassword.mas_bottom).offset(10);
        make.centerY.equalTo(self.redTipe.mas_centerY).offset(0);
        make.right.equalTo(self).offset(-15);
        make.height.mas_equalTo(20);
    }];
    
    [self.redTipe mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.fieldPassword.mas_bottom).offset(10);
        make.left.equalTo(self).offset(15);
    }];
}

-(void)addLogo{
    BaseImageV *image = [[BaseImageV alloc]initWithFrame:CGRectMake(0, 10, 78, 61)];
    if ([Main_Token_Model_MANAGER.isToken isEqualToString:@"1"]){
        image.frame = CGRectMake(0, 0, kScreenW, kScreenH);
        image.image = [UIImage imageNamed:@"WXBG"];
    }else{
        image.image = [UIImage imageNamed:@"登录logo"];
        image.centerX = self.centerX;
        image.contentMode = 2;
    }
//    image.image = [UIImage imageNamed:@"文字logo"];

    [self addSubview:image];
}



-(QMUITextField *)fieldLogin{
    if (!_fieldLogin) {
        _fieldLogin = [[QMUITextField alloc]initWithFrame:CGRectMake(0, 100, 150, 50)];
        _fieldLogin.font = [UIFont systemFontOfSize:25];
        _fieldLogin.delegate = self;
        _fieldLogin.placeholderColor = [UIColor whiteColor]; // 自定义 placeholder 的颜色
        _fieldLogin.returnKeyType = UIReturnKeyDone;
        _fieldLogin.enablesReturnKeyAutomatically = YES;
        _fieldLogin.tintColor = [UIColor colorWithHex:@"333333"];
        // 限制可输入的字符长度
//        _fieldLogin.maximumTextLength = 11;
        _fieldLogin.qmui_borderWidth = 1;
        _fieldLogin.qmui_borderPosition = QMUIViewBorderPositionBottom;
//        _fieldLogin.keyboardType = UIKeyboardTypeNumberPad;
        _fieldLogin.qmui_borderColor = [UIColor colorWithHex:@"eeeeee"];
        _fieldLogin.font = [UIFont fontWithName:@"PingFang-SC-Regular" size:15];
        
        
        NSMutableParagraphStyle *style = [[NSMutableParagraphStyle alloc] init];
        NSAttributedString *attri = [[NSAttributedString alloc] initWithString:@"输入手机号/邮箱/用户名" attributes:@{NSForegroundColorAttributeName:[UIColor colorWithHex:@"999999"],NSFontAttributeName:[UIFont fontWithName:@"PingFang-SC-Regular" size:15], NSParagraphStyleAttributeName:style}];
        _fieldLogin.attributedPlaceholder = attri;

        
    }
    return _fieldLogin;
}


-(QMUITextField *)fieldPassword{
    if (!_fieldPassword) {
        _fieldPassword = [[QMUITextField alloc]initWithFrame:CGRectMake(0, 100, 150, 50)];
        _fieldPassword.font = [UIFont systemFontOfSize:25];
        _fieldPassword.delegate = self;
        _fieldPassword.placeholderColor = [UIColor whiteColor]; // 自定义 placeholder 的颜色
        _fieldPassword.returnKeyType = UIReturnKeyDone;
        _fieldPassword.enablesReturnKeyAutomatically = YES;
        _fieldPassword.tintColor = [UIColor colorWithHex:@"333333"];
        // 限制可输入的字符长度
        _fieldPassword.maximumTextLength = 12;
        _fieldPassword.qmui_borderWidth = 1;
        _fieldPassword.qmui_borderPosition = QMUIViewBorderPositionBottom;
//        _fieldPassword.keyboardType = UIKeyboardTypeNumberPad;
        _fieldPassword.qmui_borderColor = [UIColor colorWithHex:@"eeeeee"];
        _fieldPassword.font = [UIFont fontWithName:@"PingFang-SC-Regular" size:15];
        _fieldPassword.secureTextEntry = YES;
        
        NSMutableParagraphStyle *style = [[NSMutableParagraphStyle alloc] init];
        NSAttributedString *attri = [[NSAttributedString alloc] initWithString:@"登录密码" attributes:@{NSForegroundColorAttributeName:[UIColor colorWithHex:@"999999"],NSFontAttributeName:[UIFont fontWithName:@"PingFang-SC-Regular" size:15], NSParagraphStyleAttributeName:style}];
        _fieldPassword.attributedPlaceholder = attri;
     
        
    }
    return _fieldPassword;
}

-(UIButton *)eyebtn{
    if (!_eyebtn) {
//        _eyebtn = [[BaseBtn alloc]initializeFrame:CGRectMake(kScreenW-60, 0, 32, 32) NormalImage:@"登录_不可见" SeleImage:@"登录_可见"];
        
        _eyebtn = [UIButton buttonWithType:UIButtonTypeCustom];
        _eyebtn.frame = CGRectMake(kScreenW-60, 0, 32, 32);
        _eyebtn.enabled = NO;
        _eyebtn.userInteractionEnabled =NO;
        [_eyebtn setImage:[UIImage imageNamed:@"登录_不可见"] forState:UIControlStateNormal];
        [_eyebtn setImage:[UIImage imageNamed:@"登录_可见"] forState:UIControlStateSelected];
        [_eyebtn setImage:[UIImage imageNamed:@"登录_可见（不可点击状态）"] forState:UIControlStateDisabled];

        
//        _eyebtn.backgroundColor = [UIColor redColor];
        @weakify(self);//登录_可见（不可点击状态）
        [[_eyebtn rac_signalForControlEvents:(UIControlEventTouchUpInside)] subscribeNext:^(__kindof UIControl * _Nullable x) {
            @strongify(self);
            self.eyebtn.selected = !self.eyebtn.selected;
            self.fieldPassword.secureTextEntry = !self.fieldPassword.secureTextEntry;
        }];
    }
    return _eyebtn;
}
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string
{
    self.redTipe.hidden = YES;
    
    NSString *toBeString = [textField.text stringByReplacingCharactersInRange:range withString:string];
    //明文切换密文后避免被清空
    if (textField == self.fieldPassword ){
        if (![self isConformToSpecificationsForPassword:toBeString]) {
            return NO;
        }
    }
    
    if ( textField == self.fieldLogin ) {
        //查看是否符合规范
        if (![self isConformToSpecifications:toBeString]) {
            return NO;
        }
    }
    if (textField == self.fieldPassword && textField.isSecureTextEntry) {
        textField.text = toBeString;
        if (textField.text.length == 0) {
            NSLog(@"打开禁用");
            self.eyebtn.enabled = NO;
            self.eyebtn.userInteractionEnabled =NO;
            self.loginbtn.enabled = NO;
            self.loginbtn.alpha = 0.5;
        }else{
            NSLog(@"关闭禁用");
            self.eyebtn.enabled = YES;
            self.eyebtn.userInteractionEnabled =YES;
            self.loginbtn.enabled = YES;
            self.loginbtn.alpha = 1;
        }
        return NO;
    }
    return YES;
}

-(BOOL)isConformToSpecifications:(NSString*)string{
    NSUInteger lengthOfString = string.length;//lengthOfString的值始终为1

    for (NSInteger loopIndex = 0; loopIndex < lengthOfString; loopIndex++) {
        unichar character = [string characterAtIndex:loopIndex];//将输入的值转化为ASCII值（即内部索引值），可以参考ASCII表
        if (character == 64 ||character == 46) {
            return YES;
        }
        // 48-57;{0,9};65-90;{A..Z};97-122:{a..z}
        if (character < 48) return NO; // 48 unichar for 0
        
        if (character > 57 && character < 65) return NO; //
        
        if (character > 90 && character < 97) return NO;
        
        if (character > 122) return NO;
        
    }
    return YES;
}



-(BOOL)isConformToSpecificationsForPassword:(NSString*)string{
    NSUInteger lengthOfString = string.length;//lengthOfString的值始终为1
    for (NSInteger loopIndex = 0; loopIndex < lengthOfString; loopIndex++) {
        unichar character = [string characterAtIndex:loopIndex];//将输入的值转化为ASCII值（即内部索引值），可以参考ASCII表
        //        if (character == 64 ||character == 46) {
        //            return YES;
        //        }
        // 48-57;{0,9};65-90;{A..Z};97-122:{a..z}
        if (character < 48) return NO; // 48 unichar for 0
        
        if (character > 57 && character < 65) return NO; //
        
        if (character > 90 && character < 97) return NO;
        
        if (character > 122) return NO;
        
    }
    return YES;
}

-(BaseBtn *)forgetbtn{
    if (!_forgetbtn) {
        _forgetbtn = [[BaseBtn alloc]initializeFrame:CGRectMake(0, 0, 0, 0) NormalText:@"忘记密码" NormalTextColor:baseColorTheme SeleText:nil SeleTextColor:nil font:14 isBold:NO];
        _forgetbtn.titleLabel.font = [UIFont fontWithName:@"PingFang-SC-Regular" size:12];
        _forgetbtn.backgroundColor = [UIColor clearColor];
        if ([Main_Token_Model_MANAGER.isToken isEqualToString:@"1"]){
            [_forgetbtn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
        }
        @weakify(self);
        [[_forgetbtn rac_signalForControlEvents:(UIControlEventTouchUpInside)] subscribeNext:^(__kindof UIControl * _Nullable x) {
            @strongify(self);
            MeRegisterRegisterVC * vc = [[MeRegisterRegisterVC alloc]init];
            vc.state = MeRegisterRegisterStateForget;
            [self.getNav pushViewController:vc animated:YES];
        }];
    }return _forgetbtn;
}

-(BaseBtn *)loginbtn{
    if (!_loginbtn) {
        _loginbtn = [[BaseBtn alloc]initializeFrame:CGRectMake(0, 0, 0, 0) NormalText:@"登录" NormalTextColor:[UIColor whiteColor] SeleText:nil SeleTextColor:nil font:14 isBold:NO];
        _loginbtn.backgroundColor = baseColorTheme;
        _loginbtn.titleLabel.font = [UIFont fontWithName:@"PingFangSC-Medium" size:15];
        _loginbtn.alpha = 0.5;
        _loginbtn.enabled = NO;
        [_loginbtn setCornerRadiusWithRadius:4 isMasks:YES];
        
        @weakify(self);
        [[_loginbtn rac_signalForControlEvents:(UIControlEventTouchUpInside)] subscribeNext:^(__kindof UIControl * _Nullable x) {
            @strongify(self);
            if (self.fieldPassword.text.length<6) {
                self.redTipe.hidden = NO;
                self.redTipe.text = @"密码不能少于6位";
                return ;
            }
            
            
            [[AccountService loadLoginForPassword:self.fieldLogin.text credential:self.fieldPassword.text authMethod:nil reponseObjctClass:nil]subscribeNext:^(ResponseData * x) {
                if (x.success) {
                    [kUSER_INFO_MANAGER saveCookie];
                    ResponseData *data = x;
                    UserInfoManager *model = [[UserInfoManager alloc]init];
                    
                    [model setUserInfoWithNSDictionary: data.responseRawData[@"data"]];
                    
                    model.token = [NSString stringWithFormat:@"Bearer %@",model.token];
                    [kUSER_INFO_MANAGER setUserInfoWithModel:model];
                    [kUSER_INFO_MANAGER MyList];
                    //                UserInfoManager *mdoel = [UserInfoManager defaultManager];
                    //                [self.navigationController pushViewController:[[MeVC alloc]init] animated:YES];
                    [self.getNav popToRootViewControllerAnimated:YES];
                    //绑定别名
                    [UMessage addAlias:model.userId type:@"userId" response:^(id  _Nonnull responseObject, NSError * _Nonnull error) {
                        NSLog(@"");
                    }];
                  
                    if (![data.responseRawData[@"data"][@"password"] isEqualToString:@"yes password"]) {
                        LoginSetPasswordView *cc = [[LoginSetPasswordView alloc]initWithFrame:CGRectMake(0,0, kScreenW, kScreenH)];
//                        cc.nav = self.getNav;
                        
                        [cc show];
                    }
                    }else{
                    self.redTipe.hidden = NO;
                    self.redTipe.text = x.errorInfo;
                }
            }];
        }];
        
    }
    return _loginbtn;
}

-(BaseLab *)redTipe{
    if (!_redTipe) {
        _redTipe = [[BaseLab alloc]initializeFrame:CGRectMake(0, 0, 1, 1) text:@"输入手机号错误" font:12 textColor:[UIColor colorWithHex:@"FF6F6F"] isBold:NO numberOfLines:0];
        _redTipe.font = [UIFont fontWithName:@"PingFangSC-Medium" size:12];
        _redTipe.hidden = YES;
    }
    return _redTipe;
}
@end

